package cn.huang.service.impl;

import cn.huang.dao.PermissionDao;
import cn.huang.entity.PageResult;
import cn.huang.entity.QueryPageBean;
import cn.huang.pojo.Permission;
import cn.huang.service.PermissionService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
检查项服务
 */
@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permiSsionDao;

    //权限管理分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {

        if (queryPageBean.getQueryString() != null && !queryPageBean.getQueryString().equals("")){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+ "%");
        }
        List<Permission> orderList = permiSsionDao.selectBycondition( queryPageBean.getQueryString());
        if (orderList != null){
            if ( orderList.size() < 10 || queryPageBean.getCurrentPage() > Math.round(Math.ceil((double)orderList.size()/10))){
                queryPageBean.setCurrentPage(1);
            }
        }
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Permission> page = permiSsionDao.selectBycondition(queryPageBean.getQueryString());
        Map<String,Object> map1 = new HashMap<String, Object>();
        List<Map> maps = new ArrayList<>();
        map1.put("rows",page.getResult());
        maps.add(map1);
        Map<String,Object> map2 = new HashMap<String, Object>();
        map2.put("currentPage",queryPageBean.getCurrentPage());
        maps.add(map2);
        return new PageResult(page.getTotal(),maps);
    }

    //新增权限类型
    @Override
    public void add(Permission permission) {
        permiSsionDao.add(permission);
    }

    //删除权限类型
    @Override
    public void delete(Integer id) {
        //查询当前权限管理是否和角色管理组所关联
       long count = permiSsionDao.findCountByPermissionId(id);
       if (count > 0){
           //当前权限管理被引用,不能删除
           throw new RuntimeException("当前权限管理被引用,不能删除");
       }
       permiSsionDao.deleteById(id);
    }

    //修改权限类型
    @Override
    public void edit(Permission permission) {
        permiSsionDao.edit(permission);
    }

    //根据id查询并回显
    @Override
    public Permission findById(Integer id) {
        return permiSsionDao.findById(id);
    }

    //查询权限项所有的信息
    @Override
    public List<Permission> findAll() {
        return permiSsionDao.findAll();
    }
}
